#include <stdio.h>
#include <sqlite3.h>
#include <stdlib.h>
#include <string.h>

// returns a single value from the Configuration table
// return 0 on success, and updates value
// if it finds more than one matching key, it fails
const char* get_conf(sqlite3* database, const char* key)
{
	int res;
	sqlite3_stmt *statement;
	char* str;
	char* sql = (char*)malloc(256*sizeof(char));

	sprintf_s(sql, 256, "SELECT Key,Value FROM Configuration WHERE Key='%s';", key);

	res = sqlite3_prepare_v2(database, sql, -1, &statement, 0);
	if(res == SQLITE_OK)
	{
		res = sqlite3_step(statement);
		if(res == SQLITE_ROW)
		{
			// second column is the value, hence 1 in the line below
			int size = sqlite3_column_bytes(statement,1);
			str = (char*)malloc(sizeof(char)*size);
			strcpy_s(str, size+1, (char*)sqlite3_column_text(statement, 1));
		}
	}
	else {
		printf( "could not prepare statement: %s\n", sqlite3_errmsg(database) );
	}

	free(sql);
	sqlite3_finalize(statement);
	return str;
}

int main_sqllite3test(int argc, char argv[])
{
	sqlite3* database;
	const char* filename = "etimetsrv.db";

	int res;

	if (!filename)
		res = sqlite3_open_v2(":memory:", &database, SQLITE_OPEN_READWRITE, NULL);
	else
		res = sqlite3_open_v2(filename, &database, SQLITE_OPEN_READWRITE, NULL);

	if (res != SQLITE_OK) {
		fprintf(stderr, "bad filename\n");
	}
	else {
		fprintf(stdout, "db opened\n");
	}

	fprintf(stderr, "DB_VER: %s\n", get_conf(database, "DB_VER"));
	fprintf(stderr, "APP_VER: %s\n", get_conf(database, "APP_VER"));
	
	sqlite3_close(database);

	return 0;
}